/**
 * 研发项目状态管理Store
 * 优化版 - 基于level1-4状态体系
 */
import { observable, action } from 'mobx-miniprogram';
import dayjs from 'dayjs';

// 使用try-catch处理引用错误
let cloudHelper, pageHelper;

try {
  // 尝试不同路径引入cloudHelper
  try {
    cloudHelper = require('../../../config/path_resolver.js').pageHelper;
  } catch (e1) {
    try {
      cloudHelper = require('../../../config/path_resolver.js').pageHelper;
    } catch (e2) {
      // 再尝试绝对路径
      cloudHelper = require('../../../config/path_resolver.js').pageHelper;
    }
  }
} catch (e) {
  console.warn('加载cloud_helper失败，使用备用实现');
  // 提供备用实现
  cloudHelper = {
    callCloudData: async (route, params = {}, options = {}) => {
      console.warn(`[模拟调用云函数] ${route}`, params);
      return { project: {}, stateHistory: [] };
    }
  };
}

try {
  // 尝试不同路径引入pageHelper
  try {
    pageHelper = require('../../../config/path_resolver.js').pageHelper;
  } catch (e1) {
    try {
      pageHelper = require('../../../config/path_resolver.js').pageHelper;
    } catch (e2) {
      // 再尝试绝对路径
      pageHelper = require('../../../config/path_resolver.js').pageHelper;
    }
  }
} catch (e) {
  console.warn('加载page_helper失败，使用备用实现');
  // 提供备用实现
  pageHelper = {
    showModal: (title, content) => {
      console.log(`[模拟弹窗] ${title}: ${content}`);
      if (wx && wx.showModal) {
        wx.showModal({
          title,
          content,
          showCancel: false
        });
      }
    },
    showErrorModal: (content) => {
      console.error(`[错误弹窗] ${content}`);
      if (wx && wx.showModal) {
        wx.showModal({
          title: '错误',
          content,
          showCancel: false
        });
      }
    }
  };
}

// 状态类别定义
const STATUS_CATEGORIES = {
  // 项目主状态
  LEVEL1: {
    1: { name: '项目审核', class: 'status-review' },
    2: { name: '休眠', class: 'status-dormant' },
    3: { name: '活动', class: 'status-active' },
    99: { name: '已完成', class: 'status-completed' }
  },
  
  // 项目子状态
  LEVEL2: {
    // 项目审核子状态
    'director': { name: '董事长', class: 'substatus-director' },
    'rd_manager': { name: '研发经理', class: 'substatus-manager' },
    'assignment': { name: '分配', class: 'substatus-assignment' },
    
    // 休眠子状态
    'review': { name: '审核', class: 'substatus-review' },
    'archive': { name: '归档', class: 'substatus-archive' }
  },
  
  // 活动状态
  LEVEL3: {
    'hardware_confirm': { name: '硬件确认', class: 'active-hw-confirm' },
    'hardware': { name: '硬件', class: 'active-hardware' },
    'debug': { name: '调试', class: 'active-debug' },
    'data_sync': { name: '资料同步', class: 'active-data-sync' },
    'testing': { name: '测试', class: 'active-testing' },
    'customer_confirm': { name: '客户确认', class: 'active-customer' },
    'order_preparation': { name: '订单准备', class: 'active-order' },
    'production': { name: '生产', class: 'active-production' },
    'product_feedback': { name: '待反馈', class: 'active-feedback' }
  },
  
  // 活动子状态
  LEVEL4: {
    // 硬件子状态
    'design': { name: '设计', class: 'subactive-design' },
    'review': { name: '审核', class: 'subactive-review' },
    'sample': { name: '打样', class: 'subactive-sample' },
    'prod_sample': { name: '制样', class: 'subactive-prod-sample' },
    'in_stock': { name: '在库', class: 'subactive-in-stock' },
    
    // 测试子状态
    'testing': { name: '测试中', class: 'subactive-testing' },
    'no_test_review': { name: '免测审核', class: 'subactive-no-test' }
  }
};

// 状态转换定义（根据状态机定义）
const STATE_TRANSITIONS = {
  // 项目审核状态的转换
  'review_director': [
    { eventId: 'director_approve', name: '董事长审核通过', roles: ['director', 'admin'] },
    { eventId: 'director_reject', name: '审核不通过', roles: ['director', 'admin'] }
  ],
  
  'review_rd_manager': [
    { eventId: 'rd_manager_approve', name: '研发经理审核通过', roles: ['rd_manager', 'admin'] },
    { eventId: 'rd_manager_reject', name: '审核不通过', roles: ['rd_manager', 'admin'] }
  ],
  
  'review_assignment': [
    { eventId: 'assignment_complete', name: '资源分配完成', roles: ['rd_manager', 'admin'] }
  ],
  
  // 休眠状态的转换
  'dormant_review': [
    { eventId: 'dormant_approve', name: '休眠审核通过', roles: ['rd_manager', 'admin'] },
    { eventId: 'dormant_reject', name: '休眠审核不通过', roles: ['rd_manager', 'admin'] }
  ],
  
  'dormant_archive': [
    { eventId: 'wakeup_request', name: '唤醒申请', roles: ['business', 'admin'] }
  ],
  
  // 活动状态的转换 - 硬件确认阶段
  'active_hardware_confirm': [
    { eventId: 'hw_confirm_completed', name: '无现成硬件/硬件变更', roles: ['hardware_engineer', 'admin'] },
    { eventId: 'hw_existing', name: '已有硬件/软件变更', roles: ['hardware_engineer', 'admin'] },
    { eventId: 'apply_dormant', name: '申请休眠', roles: ['business', 'admin'] }
  ],
  
  // 活动状态的转换 - 硬件阶段
  'active_hardware': [
    { eventId: 'hw_design_submit', name: '提交审核', roles: ['hardware_engineer', 'admin'] },
    { eventId: 'hw_review_approve', name: '审核通过', roles: ['rd_manager', 'admin'] },
    { eventId: 'hw_sample_complete', name: '到料完成', roles: ['purchase', 'admin'] },
    { eventId: 'hw_prod_complete', name: '样品入库', roles: ['sample_staff', 'admin'] },
    { eventId: 'hw_issue', name: '物料异常', roles: ['sample_staff', 'admin'] },
    { eventId: 'apply_debug', name: '申请样品调试', roles: ['software_engineer', 'admin'] },
    { eventId: 'apply_dormant', name: '申请休眠', roles: ['business', 'admin'] }
  ],
  
  // 活动状态的转换 - 调试阶段
  'active_debug': [
    { eventId: 'debug_complete', name: '调试完成', roles: ['software_engineer', 'admin'] },
    { eventId: 'sync_request', name: '资料同步', roles: ['software_engineer', 'admin'] },
    { eventId: 'hw_reconfirm', name: '重新确认硬件', roles: ['software_engineer', 'admin'] },
    { eventId: 'cancel_issue', name: '撤销功能问题', roles: ['software_engineer', 'admin'] },
    { eventId: 'cancel_issue_request', name: '撤销问题申请', roles: ['software_engineer', 'admin'] },
    { eventId: 'apply_dormant', name: '申请休眠', roles: ['business', 'admin'] }
  ],
  
  // 活动状态的转换 - 测试阶段
  'active_testing': [
    { eventId: 'test_pass', name: '测试通过', roles: ['test_staff', 'admin'] },
    { eventId: 'test_fail', name: '测试不通过', roles: ['test_staff', 'admin'] },
    { eventId: 'test_cancel_issue', name: '撤销功能问题', roles: ['test_staff', 'admin'] },
    { eventId: 'apply_dormant', name: '申请休眠', roles: ['business', 'admin'] }
  ],
  
  // 更多状态转换...
};

// 创建状态管理Store
export const stateStore = observable({
  // 状态数据
  projectId: '',
  projectCode: '',
  projectName: '',
  model: '',
  
  level1: 0,
  level2: '',
  level3: '',
  level4: '',
  
  statusDesc: '',
  stateHistory: [],
  
  // 状态加载标志
  isLoading: false,
  error: null,
  
  // 初始化状态
  initState: action(async function(projectId) {
    if (!projectId) throw new Error('项目ID不能为空');
    
    this.isLoading = true;
    this.error = null;
    
    try {
      // 调用云函数获取项目状态信息
      const result = await cloudHelper.callCloudData('plm_research/state', {
        projectId
      });
      
      if (!result || !result.project) {
        throw new Error('获取项目状态失败');
      }
      
      // 更新状态数据
      const project = result.project;
      
      this.projectId = project._id || '';
      this.projectCode = project.model || project.code;
      this.projectName = project.projectType || project.model;
      
      this.level1 = project.level1 || 0;
      this.level2 = project.level2 || '';
      this.level3 = project.level3 || '';
      this.level4 = project.level4 || '';
      
      this.statusDesc = project.statusDesc || '';
      this.stateHistory = result.stateHistory || [];
      
      return true;
    } catch (error) {
      console.error('[状态Store] 初始化状态错误:', error);
      this.error = error.message || '获取状态信息失败';
      throw error;
    } finally {
      this.isLoading = false;
    }
  }),
  
  // 清除状态
  clearState: action(function() {
    this.projectId = '';
    this.projectCode = '';
    this.projectName = '';
    this.model = '';
    
    this.level1 = 0;
    this.level2 = '';
    this.level3 = '';
    this.level4 = '';
    
    this.statusDesc = '';
    this.stateHistory = [];
    
    this.isLoading = false;
    this.error = null;
  }),
  
  // 获取当前状态信息
  getCurrentState: function() {
    // 获取状态名称和样式
    const level1Info = STATUS_CATEGORIES.LEVEL1[this.level1] || { name: '未知状态', class: 'status-unknown' };
    const level2Info = this.level2 ? (STATUS_CATEGORIES.LEVEL2[this.level2] || { name: this.level2, class: 'substatus-unknown' }) : null;
    const level3Info = this.level3 ? (STATUS_CATEGORIES.LEVEL3[this.level3] || { name: this.level3, class: 'active-unknown' }) : null;
    const level4Info = this.level4 ? (STATUS_CATEGORIES.LEVEL4[this.level4] || { name: this.level4, class: 'subactive-unknown' }) : null;
    
    // 构建状态显示信息
    return {
      level1: this.level1,
      level2: this.level2,
      level3: this.level3,
      level4: this.level4,
      
      level1Name: level1Info.name,
      level2Name: level2Info ? level2Info.name : '',
      level3Name: level3Info ? level3Info.name : '',
      level4Name: level4Info ? level4Info.name : '',
      
      level1Class: level1Info.class,
      level2Class: level2Info ? level2Info.class : '',
      level3Class: level3Info ? level3Info.class : '',
      level4Class: level4Info ? level4Info.class : '',
      
      statusDesc: this.statusDesc,
      statusClass: this._getStatusClass()
    };
  },
  
  // 获取允许的状态转换
  getAllowedTransitions: function() {
    // 根据当前状态获取状态键
    let stateKey = '';
    
    if (this.level1 === 1) { // 项目审核
      stateKey = `review_${this.level2}`;
    } else if (this.level1 === 2) { // 休眠
      stateKey = `dormant_${this.level2}`;
    } else if (this.level1 === 3) { // 活动
      stateKey = `active_${this.level3}`;
      
      // 如果有子活动状态，更具体的键
      if (this.level3 === 'hardware' && this.level4) {
        stateKey = `active_hardware_${this.level4}`;
      } else if (this.level3 === 'testing' && this.level4) {
        stateKey = `active_testing_${this.level4}`;
      }
    }
    
    // 获取该状态允许的转换
    return STATE_TRANSITIONS[stateKey] || [];
  },
  
  // 执行状态转换
  transitState: action(async function(eventId, data = {}) {
    if (!this.projectId) throw new Error('项目ID不能为空');
    if (!eventId) throw new Error('事件ID不能为空');
    
    this.isLoading = true;
    this.error = null;
    
    try {
      // 调用云函数执行状态转换
      const result = await cloudHelper.callCloudData('plm_research/state_transition', {
        id: this.projectId,
        eventId,
        ...data
      });
      
      if (!result || !result.project) {
        throw new Error('状态转换失败');
      }
      
      // 更新状态数据
      const project = result.project;
      
      this.level1 = project.level1 || 0;
      this.level2 = project.level2 || '';
      this.level3 = project.level3 || '';
      this.level4 = project.level4 || '';
      
      this.statusDesc = project.statusDesc || '';
      
      // 如果返回了状态历史，更新它
      if (result.stateHistory) {
        this.stateHistory = result.stateHistory;
      }
      
      return { success: true };
    } catch (error) {
      console.error('[状态Store] 执行状态转换错误:', error);
      this.error = error.message || '状态转换失败';
      return { success: false, message: this.error };
    } finally {
      this.isLoading = false;
    }
  }),
  
  // 获取格式化的状态历史
  getFormattedHistory: function() {
    if (!this.stateHistory || !this.stateHistory.length) return [];
    
    return this.stateHistory.map(item => ({
      ...item,
      operateTimeFormat: item.OPERATE_TIME ? dayjs(item.OPERATE_TIME * 1000).format('YYYY-MM-DD HH:mm') : '--',
      fromState: item.FROM_STATE || '新建',
      toState: item.TO_STATE || '--',
      actionType: item.ACTION_TYPE || 1,
      operateUserName: item.OPERATE_USER_NAME || '未知用户',
      remark: item.REMARK || ''
    }));
  },
  
  // 获取状态样式类名
  _getStatusClass: function() {
    // 基于主状态的样式类
    const mainClasses = {
      1: 'status-review',
      2: 'status-dormant',
      3: 'status-active',
      99: 'status-completed'
    };
    
    // 返回对应的样式类，默认为未知
    return mainClasses[this.level1] || 'status-unknown';
  },
  
  setProject: action(function(project) {
    this.projectId = project._id || '';
    this.projectCode = project.model || project.code;
    this.projectName = project.projectType || project.model;
    
    this.level1 = project.level1 || 0;
    this.level2 = project.level2 || '';
    this.level3 = project.level3 || '';
    this.level4 = project.level4 || '';
    
    this.statusDesc = project.statusDesc || '';
    this.stateHistory = project.stateHistory || [];
  }),
  
  reset: action(function() {
    this.projectId = '';
    this.projectCode = '';
    this.projectName = '';
    this.model = '';
    
    this.level1 = 0;
    this.level2 = '';
    this.level3 = '';
    this.level4 = '';
    
    this.statusDesc = '';
    this.stateHistory = [];
  })
});

// 导出状态分类定义
export const StatusCategories = STATUS_CATEGORIES; 